/**
 * 时间管理相关的IPC处理程序
 * 负责处理关机、重启、睡眠等时间管理功能的IPC消息
 */

const { ipcMain } = require('electron');
const { exec } = require('child_process');
const { TimeManagementChannels } = require('../common/ipc-channels');

// 存储当前的关机任务ID
let currentShutdownTaskId = null;

/**
 * 设置时间管理相关的IPC处理程序
 */
function setupTimeManagementHandlers() {
    // 立即关机
    ipcMain.on(TimeManagementChannels.IMMEDIATE_SHUTDOWN, (event) => {
        executeShutdown(event);
    });

    // 重启计算机
    ipcMain.on(TimeManagementChannels.RESTART_COMPUTER, (event) => {
        executeRestart(event);
    });

    // 睡眠计算机
    ipcMain.on(TimeManagementChannels.SLEEP_COMPUTER, (event) => {
        executeSleep(event);
    });

    // 定时关机
    ipcMain.on(TimeManagementChannels.SCHEDULE_SHUTDOWN, (event, { hour, minute }) => {
        scheduleShutdown(event, hour, minute);
    });

    // 倒计时关机
    ipcMain.on(TimeManagementChannels.COUNTDOWN_SHUTDOWN, (event, minutes) => {
        countdownShutdown(event, minutes);
    });

    // 取消关机
    ipcMain.on(TimeManagementChannels.CANCEL_SHUTDOWN, (event) => {
        cancelShutdown(event);
    });
}

/**
 * 执行立即关机
 * @param {Electron.IpcMainEvent} event - IPC事件对象
 */
function executeShutdown(event) {
    try {
        if (process.platform === 'win32') {
            exec('shutdown /s /t 0', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `关机失败: ${error.message}`);
                }
            });
        } else if (process.platform === 'darwin') {
            exec('osascript -e \'tell app "System Events" to shut down\'', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `关机失败: ${error.message}`);
                }
            });
        } else {
            exec('shutdown -h now', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `关机失败: ${error.message}`);
                }
            });
        }
        
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, '正在关机...');
    } catch (error) {
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `关机失败: ${error.message}`);
    }
}

/**
 * 执行重启
 * @param {Electron.IpcMainEvent} event - IPC事件对象
 */
function executeRestart(event) {
    try {
        if (process.platform === 'win32') {
            exec('shutdown /r /t 0', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `重启失败: ${error.message}`);
                }
            });
        } else if (process.platform === 'darwin') {
            exec('osascript -e \'tell app "System Events" to restart\'', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `重启失败: ${error.message}`);
                }
            });
        } else {
            exec('shutdown -r now', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `重启失败: ${error.message}`);
                }
            });
        }
        
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, '正在重启...');
    } catch (error) {
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `重启失败: ${error.message}`);
    }
}

/**
 * 执行睡眠
 * @param {Electron.IpcMainEvent} event - IPC事件对象
 */
function executeSleep(event) {
    try {
        if (process.platform === 'win32') {
            exec('rundll32.exe powrprof.dll,SetSuspendState 0,1,0', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `睡眠失败: ${error.message}`);
                }
            });
        } else if (process.platform === 'darwin') {
            exec('osascript -e \'tell app "System Events" to sleep\'', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `睡眠失败: ${error.message}`);
                }
            });
        } else {
            exec('systemctl suspend', (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `睡眠失败: ${error.message}`);
                }
            });
        }
        
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, '正在进入睡眠状态...');
    } catch (error) {
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `睡眠失败: ${error.message}`);
    }
}

/**
 * 设置定时关机
 * @param {Electron.IpcMainEvent} event - IPC事件对象
 * @param {number} hour - 小时
 * @param {number} minute - 分钟
 */
function scheduleShutdown(event, hour, minute) {
    try {
        // 取消之前的关机任务
        cancelShutdown(event, false);
        
        const now = new Date();
        const shutdownTime = new Date();
        shutdownTime.setHours(hour, minute, 0, 0);
        
        // 如果设置的时间已经过去，则设置为明天的这个时间
        if (shutdownTime <= now) {
            shutdownTime.setDate(shutdownTime.getDate() + 1);
        }
        
        const diffMs = shutdownTime - now;
        const diffSeconds = Math.floor(diffMs / 1000);
        
        if (process.platform === 'win32') {
            exec(`shutdown /s /t ${diffSeconds}`, (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `设置定时关机失败: ${error.message}`);
                }
            });
        } else if (process.platform === 'darwin' || process.platform === 'linux') {
            // 对于macOS和Linux，我们使用at命令或者setTimeout
            const shutdownCommand = process.platform === 'darwin' 
                ? 'osascript -e \'tell app "System Events" to shut down\'' 
                : 'shutdown -h now';
            
            currentShutdownTaskId = setTimeout(() => {
                exec(shutdownCommand);
            }, diffMs);
        }
        
        const formattedTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `已设置定时关机: ${formattedTime}`);
    } catch (error) {
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `设置定时关机失败: ${error.message}`);
    }
}

/**
 * 设置倒计时关机
 * @param {Electron.IpcMainEvent} event - IPC事件对象
 * @param {number} minutes - 分钟数
 */
function countdownShutdown(event, minutes) {
    try {
        // 取消之前的关机任务
        cancelShutdown(event, false);
        
        const seconds = minutes * 60;
        
        if (process.platform === 'win32') {
            exec(`shutdown /s /t ${seconds}`, (error) => {
                if (error) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `设置倒计时关机失败: ${error.message}`);
                }
            });
        } else if (process.platform === 'darwin' || process.platform === 'linux') {
            // 对于macOS和Linux，我们使用setTimeout
            const shutdownCommand = process.platform === 'darwin' 
                ? 'osascript -e \'tell app "System Events" to shut down\'' 
                : 'shutdown -h now';
            
            currentShutdownTaskId = setTimeout(() => {
                exec(shutdownCommand);
            }, seconds * 1000);
        }
        
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `已设置倒计时关机: ${minutes}分钟后`);
    } catch (error) {
        event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `设置倒计时关机失败: ${error.message}`);
    }
}

/**
 * 取消关机
 * @param {Electron.IpcMainEvent} event - IPC事件对象
 * @param {boolean} sendResult - 是否发送结果消息
 */
function cancelShutdown(event, sendResult = true) {
    try {
        if (process.platform === 'win32') {
            exec('shutdown /a', (error) => {
                if (error && sendResult) {
                    event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `取消关机失败: ${error.message}`);
                }
            });
        } else if (process.platform === 'darwin' || process.platform === 'linux') {
            // 对于macOS和Linux，我们清除之前设置的setTimeout
            if (currentShutdownTaskId) {
                clearTimeout(currentShutdownTaskId);
                currentShutdownTaskId = null;
            }
        }
        
        if (sendResult) {
            event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, '已取消关机设置');
        }
    } catch (error) {
        if (sendResult) {
            event.sender.send(TimeManagementChannels.SHUTDOWN_RESULT, `取消关机失败: ${error.message}`);
        }
    }
}

module.exports = {
    setupTimeManagementHandlers
};